/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *          http://www.apexes.net
 */

package net.apexes.commons.ormlite;

import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.field.types.BaseDataType;
import com.j256.ormlite.misc.SqlExceptionUtil;
import com.j256.ormlite.support.DatabaseResults;

import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 */
public class BigDecimalLongType extends BaseDataType {

    private static final BigDecimalLongType singleTon = new BigDecimalLongType();

    public static BigDecimalLongType getSingleton() {
        return singleTon;
    }

    private BigDecimalLongType() {
        // this has no classes because {@link BigDecimalString} is the default
        super(SqlType.LONG);
    }

    /**
     * Here for others to subclass.
     */
    protected BigDecimalLongType(SqlType sqlType, Class<?>[] classes) {
        super(sqlType, classes);
    }

    @Override
    public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
        try {
            return new BigDecimal(defaultStr);
        } catch (IllegalArgumentException e) {
            throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default BigDecimal string '"
                    + defaultStr + "'", e);
        }
    }

    @Override
    public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
        if (results.wasNull(columnPos)) {
            return null;
        }
        return BigDecimal.valueOf(results.getLong(columnPos));
    }

    @Override
    public boolean isAppropriateId() {
        return false;
    }

    @Override
    public boolean isEscapedValue() {
        return false;
    }

    @Override
    public Class<?> getPrimaryClass() {
        return BigDecimal.class;
    }
}
